package com.sbcb.mongodb.config;

import com.mongodb.ConnectionString;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import org.bson.codecs.configuration.CodecProvider;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.mongodb.MongoClientSettings.getDefaultCodecRegistry;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;

@Configuration
public class MongoConfig {
    @Autowired
    private MongoDBServer mongoDBServer;

    @Bean
    public MongoClient nativeMongoClient(){
        MongoClient mongoClient = MongoClients.create(mongoDBServer.getUrl());
        return mongoClient;
    }

    /**
     * https://docs.mongodb.com/drivers/java/sync/current/fundamentals/data-formats/document-data-format-pojo/
     * @return
     */
    @Bean
    public MongoDatabase mongoDatabase(){
        CodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();
        CodecRegistry pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));
        return nativeMongoClient().getDatabase(mongoDBServer.getDatabase()).withCodecRegistry(pojoCodecRegistry);
    }
}
